package com.oddfar.campus.business.service.Impl;

import com.oddfar.campus.common.domain.PageResult;
import com.oddfar.campus.common.exception.ServiceException;
import com.oddfar.campus.common.utils.SecurityUtils;
import com.oddfar.campus.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oddfar.campus.business.mapper.CzxxMapper;
import com.oddfar.campus.business.domain.Czxx;
import com.oddfar.campus.business.service.CzxxService;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class CzxxServiceImpl extends ServiceImpl<CzxxMapper, Czxx> implements CzxxService{

    @Autowired
    private CzxxMapper czxxMapper;

    // 车主信息列表查询
    @Override
    public PageResult<Czxx> page(Czxx czxx) {
        Long userId = SecurityUtils.getUserId();
        if (userId != 1) {
            return czxxMapper.selectPage(czxx, userId);
        }
        return czxxMapper.selectPage(czxx);
    }

    // 新增车主信息
    @Override
    @Transactional
    public int insertCzxx(Czxx czxx) {
        Czxx user = czxxMapper.selectById(czxx.getPhonenumber());
        if (user != null) {
            throw new ServiceException("禁止重复添加");
        }
        if (StringUtils.isNotEmpty(czxx.getPhonenumber())
                && !(checkPhoneUnique(czxx))) {
            throw new ServiceException("新增用户失败，手机号码已存在");
        }
        czxx.setUserName(czxx.getPhonenumber());
        czxx.setCreateUser(SecurityUtils.getUserId());
        czxx.setCreateTime(getNowTime());
        czxx.setDelFlag(false);
        czxx.setUserType("00");
        czxx.setPassword(SecurityUtils.encryptPassword(czxx.getPassword()));
        // 新增用户信息
        Long user__id = czxxMapper.chaxunzuidaid();
        czxx.setUserId(user__id + 1);
        czxxMapper.tongbuxitongyonghu(czxx);
        czxxMapper.tongbuquanxian(czxx);
        return czxxMapper.insert(czxx);
    }

    // 手机号查重
    public boolean checkPhoneUnique(Czxx czxx) {
        Long userId = StringUtils.isNull(czxx.getUserId()) ? -1L : czxx.getUserId();
        Czxx info = czxxMapper.checkPhoneUnique(czxx.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return false;
        }
        return true;
    }

    // 修改信息
    @Override
    public int updateCzxx(Czxx czxx) {
        if (SecurityUtils.getUserId() != 1 && !czxx.getCreateUser().equals(SecurityUtils.getUserId())) {
            throw new ServiceException("只能修改自己创建的用户");
        }
        return czxxMapper.updateById(czxx);
    }

    public Date getNowTime() {
        long time = System.currentTimeMillis();
        return new Date(time);
    }
}
